<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>红绿灯算法</title>
		<style>
			#lights_wrap {
				width: 100%;
				height: 200px;
				border: black 10px solid;
				display: flex;
				justify-content: space-around;
				align-items: center;
			}

			.light {
				width: 200px;
				height: 200px;
				border-radius: 50%;
				margin-left: 10px;
			}

			.red_light {
				background-color: red;
			}

			.yellow_light {
				background-color: yellow;
			}

			.green_light {
				background-color: green;
			}
		</style>
	</head>
	<body>
		<div id="lights_wrap">
			<div class="light red_light"></div>
			<div class="light yellow_light"></div>
			<div class="light green_light"></div>
		</div>
		<script>
			function light() {
				red_light() //红灯亮
				setTimeout(yellow_light, 1000); //黄灯一秒后亮
				setTimeout(red_light, 1000); //黄灯亮的同时关闭红灯
				setTimeout(green_light, 2000); //绿灯两秒后亮
				setTimeout(yellow_light, 2000); //绿灯亮，黄灯熄
				setTimeout(green_light, 3000); //三秒后，红灯熄
			}

			function red_light() {
				//获取红灯
				let r = document.getElementsByClassName('red_light')[0];
				//toggle函数，如果有该属性，则去除，没有该属性，则添加 
				r.classList.toggle('light')
			}

			function green_light() {
				//同上
				let r = document.getElementsByClassName('green_light')[0];
				r.classList.toggle('light')
			}

			function yellow_light() {
				//同上
				let r = document.getElementsByClassName('yellow_light')[0];
				console.log(r);
				r.classList.toggle('light')
			}

			light(); //先执行函数
			window.onload = function() {
				t1 = setInterval(light, 3000) //每隔三秒重复执行函数
			};
			//每隔三秒的时间是因为每个灯各闪一秒，如果改变了灯的持续时间，循环时间也要修改
		</script>
	</body>
</html>
